package com.zijidelu.luframework.domain.model.aggregate;

import com.zijidelu.luframework.base.bizsig.BizSignature;
import com.zijidelu.luframework.base.model.DataModel;
import com.zijidelu.luframework.domain.model.entity.ChildrenEntityVault;
import com.zijidelu.luframework.domain.model.entity.Entity;
import lombok.Getter;

import java.util.Objects;

/**
 * 抽象CRUD聚合根类。
 * <p>
 * 提供基础的CRUD操作和状态管理。
 *
 * @author ZIJIDELU
 * @datetime 2025/11/14 11:17
 */
public abstract class AbstractCrudAggregateRoot<D extends DataModel, E extends Entity<D>>
        extends AbstractDomainEventAggregateRoot {

    @Getter
    private final E rootEntity;

    private BizSignature<D> bizSignature;

    /**
     * 子实体CRUD状态映射（transient 避免序列化问题）
     */
    @Getter
    private transient final ChildrenEntityVault<E, ?> childrenEntityVault = new ChildrenEntityVault<>();

    /**
     * 核心约定：
     * <p>
     * 1. 聚合根必须有一个根实体。
     * <p>
     * 2. 根实体必须是可读写的。
     *
     * @param rootEntity 根实体
     */
    public AbstractCrudAggregateRoot(E rootEntity) {
        Objects.requireNonNull(rootEntity, "Root entity cannot be null");
        this.rootEntity = rootEntity;
    }

    protected E root() {
        return rootEntity;
    }

    protected BizSignature<D> getBizSignature() {
        return bizSignature;
    }

    protected void setBizSignature(BizSignature<D> bizSignature) {
        this.bizSignature = bizSignature;
    }

    /**
     * 准备聚合根加载
     */
    public void prepareLoad() {
        rootEntity.markAsReadState();
    }

    /**
     * 准备聚合根持久化
     */
    public void preparePersist() {
    }

    /**
     * 清除所有子实体CRUD状态映射
     */
    protected void clearChildrenEntityVault() {
        childrenEntityVault.clearVault();
    }

}
